﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;

namespace AChance.Func
{
    public static class FunZip
    {
        /// <summary>
        /// 判断是否压缩
        /// </summary>
        public static bool IsZip(byte[] content)
        {
            try
            {
                Unzip(content);
                return true;
            }
            catch
            {
                return false;
            }
        }
        /// <summary>
        /// 压缩
        /// </summary>
        public static byte[] Zip(byte[] content, bool check = false)
        {
            if (check && IsZip(content))
                return content.ToArray();
            else
            {
                using var compress = new MemoryStream();
                using (var zip = new GZipStream(compress, CompressionMode.Compress))
                    zip.Write(content, 0, content.Length);
                return compress.ToArray();
            }
        }
        /// <summary>
        /// 解压
        /// </summary>
        public static byte[] Unzip(byte[] content, bool check = false)
        {
            if (check && !IsZip(content))
                return content.ToArray();
            else
            {
                using var compress = new MemoryStream(content);
                using var decompress = new MemoryStream();
                using (var unzip = new GZipStream(compress, CompressionMode.Decompress))
                    unzip.CopyTo(decompress);
                return decompress.ToArray();
            }
        }


    }
}
